/**
 * Created by yu on 16/9/3.
 */

var http = require('http');
var url = require('url');
var fs = require('fs');
var queryString = require('querystring');
var util = require('util');
var formidable = require('formidable');
var mime = require('mime');


var server = http.createServer(function(req,res){
    var urlObj = url.parse(req.url,true);
    if(urlObj.pathname == '/'){
        res.setHeader("200",{'Content-type':'text/html;charset=utf-8'});
        fs.readFile('./index.html',function(err,data){
            res.write(data);
            res.end();
        })
    }else if(urlObj.pathname=='/post1'){
        //构建解析器
        var form = new formidable.IncomingForm();
        //接受客户端传过来的数据,将不通的input文本放进 fields里面,把上传的文件放在files中
        form.parse(req, function(err, fields, files) {
            var filename = '/images/'+files.headerPic.name;
            fs.readFile(files.headerPic.path,function(err,data){
                fs.writeFile('.'+filename,data,function(err){
                    res.setHeader('Content-Type','text/plain');
                    res.end('.'+filename);
                })
            })
        })
    }else{
        pathname = urlObj.pathname;
        fs.exists('.'+pathname,function(exists){
            if(exists){
                res.setHeader('Content-Type',mime.lookup(pathname));
                fs.readFile('.'+pathname,function(err,data){
                    res.end(data);
                })
            }else{
                res.statusCode = 404;
                res.end('404');
            }
        })
    }
})
//批量上传,找上期,2015年第9期.http上传 128分钟

server.listen(8081,'localhost');

